﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Web;
using System.Security.Cryptography;

namespace WaterWay.Utilities
{
    /// <summary>
    /// MD5加密帮助类
    public class Md5Helper
    {
        #region "MD5加密"
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string MD52(string str, int code)
        {
            string strEncrypt = string.Empty;
            if (code == 16)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16);
            }

            if (code == 32)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            }

            return strEncrypt;
        }
        #endregion


        #region MD5加密

        /// <summary>
        /// 获取MD5哈希值
        /// </summary>
        /// <param name="Text">字符串</param>
        /// <returns>MD5哈希值</returns>
        public static string GetMd5Hash(string Text)
        {
            MD5 md5 = MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(Text));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }
            return builder.ToString();
        }

        /// <summary>
        /// 验证MD5哈希值
        /// </summary>
        /// <param name="Text">字符串</param>
        /// <param name="TextHash">哈希值</param>
        /// <returns>相同返回True,不同返回False</returns>
        public static bool VerifyMd5Hash(string Text, string TextHash)
        {
            string hash = GetMd5Hash(Text);
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            if (0 == comparer.Compare(hash, TextHash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
    }
}
